import Api from '@/common/api.js'

const DICT_KEY = 'DICT'
 let dictData = {
	"dictKey": "dict",
	"dictValue": "字典",
	"childNode": {
		selector: {
			"dictKey": "selector",
			"dictValue": "选择器",
			"childNode": {}
		},
		order_status: {
			"dictKey": "order_status",
			"dictValue": "订单状态",
			"childNode": {}
		}
	}
};

function initDictData () {
	uni.setStorageSync(DICT_KEY,dictData);
	console.log('initDictData');
	initSelectorDictData();
	initOrderStatusDictData();
}

function initSelectorDictData() {
	console.log('initSelectorDictData');
	Api.get({
		url: `/open/dict/selector`,
	}).then(res => {
		let dictData = uni.getStorageSync(DICT_KEY);
		dictData.childNode['selector'].childNode = res.data.data;
		uni.setStorageSync(DICT_KEY,dictData);
	});
}

function initOrderStatusDictData() {
	console.log('initOrderStatusDictData');
	Api.get({
		url: `/open/dict/orderStatus`,
	}).then(res => {
		let dictData = uni.getStorageSync(DICT_KEY);
		dictData.childNode['order_status'].childNode = res.data.data;
		uni.setStorageSync(DICT_KEY,dictData);
	});
}

function get(...key) {
	let keyCache = key.slice(0);
	let shot = false;
	let dictData = uni.getStorageSync(DICT_KEY);
	let dictCache = JSON.parse(JSON.stringify(dictData));
	while (!shot) {
		let keyItem = keyCache.shift();
		if (typeof keyItem === 'undefined' || keyItem == null) {
			shot = true;
			break;
		}
		dictCache = dictCache.childNode[keyItem] || dictCache;
	}
	return dictCache;
}

function getValue(...key) {
	return get.apply(this,key).dictValue;
}

function getChild(...key) {
	return get.apply(this,key).childNode;
}

function getSelector(...key) {
	key = key || [];
	key.unshift('selector');
	return getValue.apply(this,key);
}

function getSelectors(...key) {
	console.log('getSelectors...')
	key = key || [];
	key.unshift('selector');
	let res = [];
	let content = getChild.apply(this,key);
	if (content && Object.keys(content).length > 0) {
		for(let key in content) {
		   res.push(content[key])
		}
	}
	return res;
}

function log(...key) {
	console.log('log..', key)
}

export default {
	initDictData,
	initSelectorDictData,
	get,
	getValue,
	getChild,
	getSelector,
	getSelectors,
	log
}
